<?php

namespace App\Service;

use App\Model\UserModel;
use App\Model\UtilSmsModel;
use App\Utility\DataConversion;
use App\Utility\JwtManager;
use App\Utility\Password;
use EasySwoole\HttpClient\Exception\InvalidUrl;
use EasySwoole\ORM\Exception\Exception;
use Throwable;

class LoginService extends BaseService
{
    /**
     * @param $username
     * @param $avatar
     * @param $sex
     * @param $we_code
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws InvalidUrl
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function weLogin($username, $avatar, $sex, $we_code, $ip): array
    {
        $param = UserService::getInstance()->getWechatOpenId($we_code);
        if (!$param['result']) {
            return [
                'result' => false,
                'msg' => '登录失败'
            ];
        }
        $openId = $param['data'];

        /*$p = UserService::getInstance()->getWechatPhone($we_code);
        if (!$p['result']) {
            return [
                'result' => false,
                'msg' => '手机号获取失败'
            ];
        }
        $phone = $p['data']['phoneNumber'] ?? '';*/
        user:
        $user = UserModel::create()->getUser(['we_code' => $openId]);
        if (!$user) {
            $par = [
                'userid' => DataConversion::getInstance()->get_random(8),
                'username' => $username,
                'avatar' => $avatar,
                'sex' => $sex,
                'we_code' => $openId,
                //'phone' => $phone
            ];

            $res = UserModel::create()->addUser($par);
            if (!$res) {
                return [
                    'result' => false,
                    'msg' => '登录失败'
                ];
            }

            goto user;
        }

        return $this->loginResult($user, $ip);
    }

    /**
     * @param $phone
     * @param $code
     * @param $requestId
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function codeLogin($phone, $code, $requestId, $ip): array
    {
        $sms = UtilSmsModel::create()->getEmail(['requestId' => $requestId]);
        if (!$sms) {
            return [
                'result' => false,
                'msg' => '验证失败'
            ];
        }
        if ($sms->code !== $code * 1) {
            return [
                'result' => false,
                'msg' => '验证码输入错误'
            ];
        }
        if ((time() - $sms->create_time) > 300) {
            return [
                'result' => false,
                'msg' => '当前任务已超时，请重新验证'
            ];
        }

        user:
        $user = UserModel::create()->getUser(['phone' => $phone]);
        if (!$user) {
            $par = [
                'userid' => DataConversion::getInstance()->get_random(8),
                'username' => '用户_' . date("Ymd") . DataConversion::getInstance()->get_random(4),
                'phone' => $phone
            ];

            $res = UserModel::create()->addUser($par);
            if (!$res) {
                return [
                    'result' => false,
                    'msg' => '登录失败'
                ];
            }
            goto user;
        }

        UserService::getInstance()->bindHouse($user->id, $phone);

        return $this->loginResult($user, $ip);
    }

    /**
     * @param $user
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function loginResult($user, $ip): array
    {
        UserModel::create()->update(['login_time' => time(), 'login_ip' => $ip], ['id' => $user->id]);
        $user->password = '';

        $userJwt = JwtManager::getInstance()->encode($user->id, $user->userid, $user->username);
        $users = $user->toArray();
        $data = $users;
        $data['token'] = $userJwt;
        return [
            'result' => true,
            'msg' => '登陆成功',
            'data' => $data
        ];
    }

    /**
     * @param $username
     * @param $password
     * @param $ip
     * @return array
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function passLogin($username, $password, $ip): array
    {
        $user = UserModel::create()->getUser(['userid' => $username]);
        if (!$user) {
            $user = UserModel::create()->getUser(['phone' => $username]);
            if (!$user) {
                return [
                    'result' => false,
                    'msg' => '账户不存在'
                ];
            }
        }
        if (!Password::getInstance()->validate($password, $user->password)) {
            return [
                'result' => false,
                'msg' => '账户密码不匹配'
            ];
        }

        return $this->loginResult($user, $ip);
    }
}